/**
 * @file OrderManagement.jsx
 * @description 后台管理系统的订单管理页面组件
 */
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { 
  Table, Card, Typography, Space, Button, Tag, Modal, 
  Form, Select, Input, Drawer, Descriptions, Badge, Divider, List, Image 
} from 'antd';
import { 
  ReloadOutlined, SearchOutlined, EyeOutlined, 
  CheckOutlined, CloseOutlined, SendOutlined 
} from '@ant-design/icons';
import { fetchAllOrders, updateOrder } from '../store/ordersSlice';
import toast from 'react-hot-toast';

const { Title } = Typography;
const { Option } = Select;

const OrderManagement = () => {
  const dispatch = useDispatch();
  const { orders, isLoading } = useSelector((state) => state.orders);
  const [filteredOrders, setFilteredOrders] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [viewOrder, setViewOrder] = useState(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    dispatch(fetchAllOrders());
  }, [dispatch]);

  useEffect(() => {
    if (orders.length > 0) {
      let filtered = [...orders];
      
      if (statusFilter !== 'all') {
        filtered = filtered.filter(order => order.status === statusFilter);
      }
      
      if (searchText) {
        filtered = filtered.filter(order => 
          order.orderId.toLowerCase().includes(searchText.toLowerCase()) ||
          order.shippingAddress.fullName.toLowerCase().includes(searchText.toLowerCase())
        );
      }
      
      filtered.sort((a, b) => new Date(b.date) - new Date(a.date));
      
      setFilteredOrders(filtered);
    } else {
      setFilteredOrders([]);
    }
  }, [orders, statusFilter, searchText]);

  const handleSearch = (value) => {
    setSearchText(value);
  };

  const handleStatusFilterChange = (value) => {
    setStatusFilter(value);
  };

  const handleRefresh = () => {
    dispatch(fetchAllOrders());
    toast.success('订单数据已刷新');
  };

  const showOrderDetails = (order) => {
    setViewOrder(order);
    setDrawerVisible(true);
  };

  const closeDrawer = () => {
    setDrawerVisible(false);
  };

  const showUpdateModal = (order) => {
    setCurrentOrder(order);
    form.setFieldsValue({ status: order.status });
    setUpdateModalVisible(true);
  };

  const handleUpdateCancel = () => {
    setUpdateModalVisible(false);
    setCurrentOrder(null);
    form.resetFields();
  };

  const handleUpdateSubmit = async () => {
    try {
      const values = await form.validateFields();
      // 直接等待手动 thunk 返回的布尔结果
      const wasSuccessful = await dispatch(updateOrder(currentOrder.orderId, values.status));
      
      if (wasSuccessful) {
        toast.success(`订单 ${currentOrder.orderId} 状态已更新为 ${values.status}`);
        setUpdateModalVisible(false);
        setCurrentOrder(null);
        form.resetFields();
      } else {
        // 此分支在 updateOrder thunk 内部捕获错误并明确返回 false 时执行
        toast.error('更新订单状态失败');
        // 即使thunk报告失败，也关闭模态框以保持一致性
        setUpdateModalVisible(false);
        setCurrentOrder(null);
        form.resetFields();
      }
    } catch (errorInfo) {
      // 此 catch 主要用于处理 form.validateFields() 的错误，
      // 或 dispatch(updateOrder(...)) 本身抛出的、未被 thunk 内部捕获的严重错误。
      console.error('表单验证或提交更新失败:', errorInfo);
      // 避免在表单验证错误时显示通用toast，AntD表单会自行处理字段错误提示
      // errorInfo.errorFields 是 AntD 表单校验错误时特有的属性
      if (!errorInfo.errorFields) { 
        toast.error('提交更新时发生意外错误。');
      }
    }
  };

  const statusColors = {
    '处理中': 'processing',
    '已发货': 'warning',
    '已完成': 'success',
    '已取消': 'error',
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '客户名称',
      dataIndex: 'shippingAddress',
      key: 'customerName',
      render: (shippingAddress) => shippingAddress.fullName,
    },
    {
      title: '订单日期',
      dataIndex: 'date',
      key: 'date',
      render: (date) => new Date(date).toLocaleDateString('zh-CN'),
    },
    {
      title: '金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={statusColors[status] || 'default'}>{status}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => showOrderDetails(record)}
          >
            查看
          </Button>
          <Button 
            type="text" 
            icon={<SendOutlined />} 
            onClick={() => showUpdateModal(record)}
            disabled={record.status === '已取消'}
          >
            更新状态
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>订单管理</Title>
      
      <Card style={{ marginBottom: 16 }}>
        <Space style={{ marginBottom: 16 }}>
          <Input.Search
            placeholder="搜索订单号或客户名称"
            allowClear
            onSearch={handleSearch}
            style={{ width: 250 }}
          />
          <Select
            defaultValue="all"
            style={{ width: 120 }}
            onChange={handleStatusFilterChange}
          >
            <Option value="all">全部状态</Option>
            <Option value="处理中">处理中</Option>
            <Option value="已发货">已发货</Option>
            <Option value="已完成">已完成</Option>
            <Option value="已取消">已取消</Option>
          </Select>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
          >
            刷新
          </Button>
        </Space>
        
        <Table 
          columns={columns} 
          dataSource={filteredOrders.map(order => ({ ...order, key: order.orderId }))} 
          loading={isLoading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Drawer
        title="订单详情"
        placement="right"
        width={600}
        onClose={closeDrawer}
        open={drawerVisible}
      >
        {viewOrder && (
          <>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="订单号">{viewOrder.orderId}</Descriptions.Item>
              <Descriptions.Item label="订单日期">
                {new Date(viewOrder.date).toLocaleString('zh-CN')}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Badge 
                  status={statusColors[viewOrder.status] === 'success' ? 'success' : 
                          statusColors[viewOrder.status] === 'error' ? 'error' : 
                          statusColors[viewOrder.status] === 'warning' ? 'warning' : 'processing'} 
                  text={viewOrder.status} 
                />
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {viewOrder.paymentMethod === 'credit' ? '信用卡' : '其他'}
              </Descriptions.Item>
            </Descriptions>

            <Divider orientation="left">客户信息</Divider>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="客户姓名">{viewOrder.shippingAddress.fullName}</Descriptions.Item>
              <Descriptions.Item label="联系邮箱">{viewOrder.shippingAddress.email}</Descriptions.Item>
              <Descriptions.Item label="配送地址">
                {`${viewOrder.shippingAddress.address}, ${viewOrder.shippingAddress.address2 || ''}, 
                ${viewOrder.shippingAddress.state}, ${viewOrder.shippingAddress.country}, ${viewOrder.shippingAddress.zip}`}
              </Descriptions.Item>
            </Descriptions>

            <Divider orientation="left">订单商品</Divider>
            <List
              itemLayout="horizontal"
              dataSource={viewOrder.items}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Image width={50} src={item.image} />}
                    title={item.title}
                    description={`单价: ¥${item.price.toFixed(2)} × ${item.qty} = ¥${(item.price * item.qty).toFixed(2)}`}
                  />
                </List.Item>
              )}
            />

            <Divider orientation="left">订单金额</Divider>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="商品小计">¥{viewOrder.subtotal.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="运费">¥{viewOrder.shipping.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="订单总额">
                <span style={{ color: '#cf1322', fontWeight: 'bold' }}>¥{viewOrder.totalAmount.toFixed(2)}</span>
              </Descriptions.Item>
            </Descriptions>
          </>
        )}
      </Drawer>

      <Modal
        title="更新订单状态"
        open={updateModalVisible}
        onCancel={handleUpdateCancel}
        footer={[
          <Button key="cancel" onClick={handleUpdateCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleUpdateSubmit}>
            确认更新
          </Button>,
        ]}
      >
        {currentOrder && (
          <Form form={form} layout="vertical">
            <Form.Item
              name="status"
              label="订单状态"
              rules={[{ required: true, message: '请选择订单状态' }]}
            >
              <Select>
                <Option value="处理中">处理中</Option>
                <Option value="已发货">已发货</Option>
                <Option value="已完成">已完成</Option>
                <Option value="已取消">已取消</Option>
              </Select>
            </Form.Item>
            <p>订单号: {currentOrder.orderId}</p>
            <p>客户: {currentOrder.shippingAddress.fullName}</p>
            <p>当前状态: <Tag color={statusColors[currentOrder.status]}>{currentOrder.status}</Tag></p>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default OrderManagement;